package com.ruoyi.controller;

import com.ruoyi.domain.DeviceData;
import com.ruoyi.domain.DeviceDetails;
import com.ruoyi.service.DeviceDataService;
import com.ruoyi.service.DeviceDataShardingService;
import com.ruoyi.service.DeviceDetailsService;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@Controller
public class LotController {

    @Resource
    DeviceDataService deviceDataService;

    @Resource
    DeviceDetailsService deviceDetailsService;

    @Resource
    DeviceDataShardingService deviceDataShardingService;

    /**
     * 获得硬件设备列表
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getDeviceDetailsList")
    public Object getDeviceDetailsList() {
        List<DeviceDetails> list = deviceDetailsService.getList();
        return list;
    }

    /**
     * 根据设备id获取该设备的温湿度数据
     *
     * @param sensorId
     * @param size
     * @return
     */
    @ResponseBody
    @GetMapping("/getDeviceDataBySensorIdList")
    public Object getDeviceDataBySensorIdList(String sensorId, int size) {
        LocalDate localDate = LocalDate.now();
        // 通过分表方式获取设备数据
        List<DeviceData> list = deviceDataShardingService.getLatestDeviceDataBeforeDate(localDate, size, sensorId);
        return list;
    }


    /**
     * 从mqtt中间件中同步硬件数据
     *
     * @param deviceData
     * @return
     */
    @ResponseBody
    @PostMapping("/addDeviceData")
    public Object addDeviceData(@RequestBody DeviceData deviceData) {
        deviceData.setCreateTime(new Date());
        System.out.println(deviceData);
        //不分表-新增数据
        //deviceDataService.addDeviceData(deviceData);
        //分表-新增数据
        deviceDataShardingService.saveDeviceData(deviceData);
        return deviceData;
    }

    /**
     * 添加设备信息
     *
     * @param deviceDetails
     * @return
     */
    @ResponseBody
    @PostMapping("/addDeviceDetails")
    public Object addDeviceDetails(@RequestBody DeviceDetails deviceDetails) {
        deviceDetails.setCreateTime(new Date());
        int result = deviceDetailsService.addDeviceData(deviceDetails);
        if (result > 0) {
            return AjaxResult.success("添加成功", deviceDetails);
        } else {
            return AjaxResult.error("添加失败");
        }
    }
}
